package com.example.projects;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.Facebook;


public class Product extends Fragment {
	private View root;
	private ViewGroup container;
	private String message;
	private Facebook fb;
	private SharedPreferences mPrefs;
	private OnSharedPreferenceChangeListener prefListener;
	
	public static Fragment newInstance(Context context) {
		Product f = new Product();	

		return f;
	}
	
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup contain,Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mPrefs = getActivity().getSharedPreferences("", Context.MODE_PRIVATE);
        prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        	  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        		  // check if token set and update UI
        		  if(prefs.getString("access_token", null) != null) {
        			  // logged in
        			  loginUpdateUI();
        		  }else {
        			  // logged out
        			  logoutUpdateUI();
        		  }
        		  
        	  }
        };
        mPrefs.registerOnSharedPreferenceChangeListener(prefListener);
        
        container = contain;
        root = (ViewGroup) inflater.inflate(R.layout.product, null);
        // Get the message from the intent
        Intent intent = getActivity().getIntent();
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
        fb = ((CPT3004)getActivity().getApplication()).getFacebook();
    	if(fb == null) {
    		// create new facebook
    		fb = new Facebook(((CPT3004)getActivity().getApplication()).getAppID());
    		
    		// prepare facebook for use
        	String access_token = mPrefs.getString("access_token", null);
        	long expires = mPrefs.getLong("access_expires", 0);
        	
        	// reuse old token if possible
        	if (access_token != null) {
    	    	fb.setAccessToken(access_token);
	        	if(expires != 0) {
	        		fb.setAccessExpires(expires);
	        	}
	        	fb.extendAccessTokenIfNeeded(getActivity().getApplicationContext(), null);
        	}
    		// store facebook
    		((CPT3004)getActivity().getApplication()).setFacebook(fb);
    	}
        
        
        
        //Read JSON file
        
    		String str = "";
    		String namestr = "";
    		String descriptionstr = "";
    		String sustainabilitystr = "";
    		String imagestr = "";
    		String energystr = "";
    		String waterstr = "";
    		String CO2str = "";
    		
			try {
				str = readFile();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("before JSON");
			System.out.println(str);
			try {
        		JSONObject json_data = new JSONObject(str);
        		namestr = json_data.getString("Name");
        		descriptionstr = json_data.getString("Description");
        		sustainabilitystr = json_data.getString("Sustainability");
        		imagestr = json_data.getString("Image");
        		energystr = json_data.getString("Energy");
        		waterstr = json_data.getString("Water");
        		CO2str = json_data.getString("CO2");

			} catch (JSONException e) {
				
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				Toast.makeText(container.getContext(), "No product data exists.", Toast.LENGTH_SHORT).show();
			}
    		
		
        message = intent.getStringExtra(Main.BARCODE);
        //setContentView(R.layout.product);
        
    	Button b = (Button) root.findViewById(R.id.favor);
    	b.setOnClickListener(new OnClickListener() {
			public void onClick(View v) 
			{
				try {
					fav();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		      	Intent intent = getActivity().getIntent();
		    	String barcode = intent.getStringExtra(Main.BARCODE);
		    	Intent intent2 = new Intent();
		    	intent2.setClassName("com.example.projects", "com.example.projects.Main");
		    	//direct the barcode to comment class
		    	intent2.putExtra(Main.BARCODE, barcode);
		    	intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		    	startActivity(intent2);
			}
    	});
    	
    	Button c = (Button) root.findViewById(R.id.com);
    	c.setOnClickListener(new OnClickListener() {
			public void onClick(View v) 
			{
		    	Intent intent = getActivity().getIntent();
		    	String barcode = intent.getStringExtra(Main.BARCODE);
    	    	AccessDatabase ad = new AccessDatabase(getActivity());
    	    	ad.execute(barcode, getActivity().getFilesDir().getAbsolutePath(), "comment");
			}
    	});

    	Button pclear = (Button) root.findViewById(R.id.productclear);
    	pclear.setOnClickListener(new OnClickListener() {
			public void onClick(View v) 
			{

		    	EditText editText = (EditText) root.findViewById(R.id.proflagcom);
		    	//set edit box text to empty string
		    	editText.setText("");
			}
    	});
    	
    	
    	Button d = (Button) root.findViewById(R.id.google);
    	d.setOnClickListener(new OnClickListener() {
			public void onClick(View v) 
			{
		    	Intent intent = getActivity().getIntent();
		    	String barcode = intent.getStringExtra(Main.BARCODE);
		    	Intent intent2 = new Intent();
		    	intent2.setClassName("com.example.projects", "com.example.projects.GoogleMaps");
		    	//direct the barcode to comment class
		    	intent2.putExtra(Main.BARCODE, barcode);
		    	intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		    	startActivity(intent2);
			}
    	});
    	EditText et = ((EditText)root.findViewById(R.id.proflagcom));
    	
    	Button f = (Button) root.findViewById(R.id.flag);
    	if(fb.isSessionValid()) {
    		f.setVisibility(View.VISIBLE);
    		et.setVisibility(View.VISIBLE);
    		pclear.setVisibility(View.VISIBLE);
    	}else{
    		f.setVisibility(View.GONE);
    		et.setVisibility(View.GONE);
    		pclear.setVisibility(View.GONE);
    	}
    	
    	f.setOnClickListener(new OnClickListener(){
    		public void onClick(View v){
    	    	// get user comment/reason for flagging and post to database
    	    	sendComment();
    		}
    	});

    	
    	
    	TextView productinfo = (TextView) root.findViewById(R.id.productinfo);
		productinfo.setText(namestr);
		productinfo.setTextSize(30);
        
        TextView barcode = (TextView) root.findViewById(R.id.barcode);
        barcode.setTextSize(20);
        barcode.setText(message);

        //Change later into button and drop down boxes
        
        /*TextView name = (TextView) root.findViewById(R.id.name);
        name.setTextSize(20);
        name.setText("Product Name: "+namestr);*/
        
        TextView description = (TextView) root.findViewById(R.id.description);
        description.setTextSize(20);
        description.setText(descriptionstr);
        
/*        TextView sustainability = (TextView) root.findViewById(R.id.sustainability);
        sustainability.setTextSize(20);
        sustainability.setText("Sustainability: "+sustainabilitystr);
*/        
        RatingBar susrat = (RatingBar) root.findViewById(R.id.ratingsustainability);
        susrat.setRating(Float.parseFloat(sustainabilitystr));
        
/*        TextView energy = (TextView) root.findViewById(R.id.energy); 
        energy.setTextSize(20);
        energy.setText("Energy: "+energystr);
*/        
        RatingBar energyrat = (RatingBar) root.findViewById(R.id.ratingenergy);
        energyrat.setRating(Float.parseFloat(energystr));
        
/*        TextView water = (TextView) root.findViewById(R.id.water); 
        water.setTextSize(20);
        water.setText("Water: "+waterstr);
*/        
        RatingBar waterrat = (RatingBar) root.findViewById(R.id.ratingwater);
        waterrat.setRating(Float.parseFloat(waterstr));
        
/*        TextView CO2 = (TextView) root.findViewById(R.id.CO2);
        CO2.setTextSize(20);
        CO2.setText("CO2: "+CO2str);
*/        
        RatingBar co2rat = (RatingBar) root.findViewById(R.id.ratingco2);
        co2rat.setRating(Float.parseFloat(CO2str));
        
        // get image if necessary otherwise use the old one
	    ImageView image = (ImageView) root.findViewById(R.id.productimage);
	    getImage gi = new getImage(container.getContext(), image);
	    gi.execute(imagestr);
        
		String str2 = "";
		String allergenstr = "";
		try {
			str2 = readAllergenFile();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if(!str2.isEmpty()) {
				JSONArray json_array = new JSONArray(str2);
				System.out.println(json_array.get(0));
	    		
				for(int i = 0; i < json_array.length(); i++){
					JSONObject json_data = (JSONObject) json_array.get(i);
		    		allergenstr = allergenstr + json_data.getString("Allergen") + "\n";
				}
			}else {
				allergenstr = "None";
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(container.getContext(), "No allergen data exists.", Toast.LENGTH_SHORT).show();
		}
        TextView allergen = (TextView) root.findViewById(R.id.allergen);
        allergen.setTextSize(20);
        allergen.setText(allergenstr);
        saveHistory();

		return root;
        
	}

    private void logoutUpdateUI(){
    	EditText et = ((EditText)root.findViewById(R.id.proflagcom));
    	et.setVisibility(View.GONE);
    	Button f = (Button)root.findViewById(R.id.flag);
    	f.setVisibility(View.GONE);
    	Button pclear = (Button)root.findViewById(R.id.productclear);
    	pclear.setVisibility(View.GONE);
    }
    
    private void sendComment(){
    	EditText l = (EditText)root.findViewById(R.id.proflagcom);
    	String text = l.getText().toString();
    	Flagging fl = new Flagging(getActivity());
    	Facebook fb = ((CPT3004)getActivity().getApplication()).getFacebook();
    	MyFacebook.setUsernameID((CPT3004)getActivity().getApplication());
    	if (fb.isSessionValid()) {
        	String name = ((CPT3004)getActivity().getApplication()).getFBName();
        	String id = ((CPT3004)getActivity().getApplication()).getFBID();
    		fl.execute(message, text, id, name);
    	}
    }
    
    private void loginUpdateUI(){
    	EditText et = ((EditText)root.findViewById(R.id.proflagcom));
    	et.setVisibility(View.VISIBLE);
    	Button f = (Button)root.findViewById(R.id.flag);
    	f.setVisibility(View.VISIBLE);
    	Button pclear = (Button)root.findViewById(R.id.productclear);
    	pclear.setVisibility(View.VISIBLE);
    }
    
	private String readFile() throws FileNotFoundException, IOException {

		Intent intent = getActivity().getIntent();
		String message = intent.getStringExtra(Main.BARCODE);
		FileInputStream stream = new FileInputStream(new File(container.getContext().getFilesDir().getAbsolutePath()+"/" + message + "product.json"));
		FileChannel fc = stream.getChannel();
		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		String str = Charset.defaultCharset().decode(bb).toString();
		stream.close();
		System.out.println("readFile: "+str);
		return str;
	}
	
    private void saveHistory(){
    	Integer count = 0;
    	ArrayList<String> histList = new ArrayList<String>();
    	File newxmlfile = new File(container.getContext().getFilesDir().getAbsolutePath() + "/hist.xml");
    	System.out.println("b");
    	try {
    		if(!newxmlfile.exists()){
    			newxmlfile.createNewFile();
        		FileOutputStream fileos = null;
        	    fileos = new FileOutputStream(newxmlfile);
        	    XmlSerializer serializer = Xml.newSerializer();
        	    
        	    serializer.setOutput(fileos, "UTF-8");
        	    serializer.startDocument("UTF-8", Boolean.valueOf(true));
        	    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        	    
        	    serializer.startTag(null, "historyitem");
        	  	serializer.text(message);
        	  	serializer.endTag(null,"historyitem");
        	  	serializer.endDocument();
        	  	serializer.flush();
        	  	fileos.close();
    		}
    		else {
    	        
    		    XmlPullParserFactory factory;
    			try {
    				factory = XmlPullParserFactory.newInstance();
    				factory.setValidating(false);
    		        XmlPullParser xpp = factory.newPullParser();
    		        //getFilesDir().getAbsolutePath()
    		        File f = new File(container.getContext().getFilesDir().getAbsolutePath()+"/hist.xml");
    		        //InputStream raw = getActivity().getApplicationContext().getAssets().open("/data/data/com.example.projects/files/fav.xml");
    		        FileInputStream fis = new FileInputStream(f);
    		        xpp.setInput(fis, "UTF-8");
    		        int eventType = xpp.getEventType();
    		        while (eventType != XmlPullParser.END_DOCUMENT) {
    			        if(eventType == XmlPullParser.START_DOCUMENT) {
    			        	System.out.println("start document");	        
    			        } else if(eventType == XmlPullParser.START_TAG) {
    			            //favlist.add(xpp.getName());
    			        	System.out.println("1");
    			        } else if(eventType == XmlPullParser.END_TAG) {
    			            //favlist.add(xpp.getName());
    			        	System.out.println("2");
    			        } else if(eventType == XmlPullParser.TEXT) {
    			            histList.add(xpp.getText());
        		        	count++;
    			        }
    		        	eventType = xpp.next();
    		        }
    		        Boolean ok = true;
    		        for (int i = 0; i < histList.size(); i++){
    		        	if(histList.get(i).equals(message)){
    		        		ok = false;
    		        	}
    		        }
    		       
    		        if (ok == true){
		        		File newxmlfile2 = new File(container.getContext().getFilesDir().getAbsolutePath() + "/hist.xml");
		        		FileOutputStream fileos2;
	        			fileos2 = new FileOutputStream(newxmlfile2);

	        			XmlSerializer serializer2 = Xml.newSerializer();
	        	    
	        		    serializer2.setOutput(fileos2, "UTF-8");
	        		    serializer2.startDocument("UTF-8", Boolean.valueOf(true));
	        		    serializer2.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    		        	
    	        	    serializer2.startTag(null, "historyitem");
    	        	    serializer2.text(message);
    	        	    serializer2.endTag(null, "historyitem");
    	        	    //History list shows one more than the number listed
    		        	if(count > 9) {
    		        		System.out.println("startcount");
    		        		System.out.println("countnumber"+count);
    		        		System.out.println("endcount");



    		        		    for(int i = histList.size()-2; i >= 0 ; i--){
    		        		    	serializer2.startTag(null, "historyitem");
    		        		  		serializer2.text(histList.get(i));
    		        		  		serializer2.endTag(null,"historyitem");
    		        		    }

    		        	}
    		        	else{
    		        		System.out.println("startcount");
    		        		System.out.println("countnumber"+count);
    		        		System.out.println("endcount");

    		        		    for(int i = histList.size()-1; i >= 0 ; i--){
    		        		    	serializer2.startTag(null, "historyitem");
    		        		  		serializer2.text(histList.get(i));
    		        		  		serializer2.endTag(null,"historyitem");
    		        		    }

    		        	}

	        		  	serializer2.endDocument();
	        		  	serializer2.flush();
	        		  	fileos2.close();
    		        }
    			} catch (XmlPullParserException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}	
    		}

    	} catch(Exception e) {
    	     Log.e("Exception","Exception occured in writing");
    	}
        
    }
	
	private String readAllergenFile() throws FileNotFoundException, IOException {
		Intent intent = getActivity().getIntent();
		String message = intent.getStringExtra(Main.BARCODE);
		FileInputStream stream = new FileInputStream(new File(container.getContext().getFilesDir().getAbsolutePath()+"/" + message + "allergen.json"));
		FileChannel fc = stream.getChannel();
		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		String str = Charset.defaultCharset().decode(bb).toString();
		stream.close();
		return str;
	}
	

    
    public void fav() throws IOException{

        // Get the message from the intent
        Intent intent = getActivity().getIntent();

        String message = intent.getStringExtra(Main.BARCODE);
    	

        Integer count = 0;
        ArrayList<String> favlist = new ArrayList<String>();
    	File newxmlfile = new File(container.getContext().getFilesDir().getAbsolutePath() + "/fav.xml");
    	System.out.println("b");
    	try {
    		if(!newxmlfile.exists()){
    			newxmlfile.createNewFile();
        		FileOutputStream fileos = null;
        	    fileos = new FileOutputStream(newxmlfile);
        	    XmlSerializer serializer = Xml.newSerializer();
        	    
        	    serializer.setOutput(fileos, "UTF-8");
        	    serializer.startDocument("UTF-8", Boolean.valueOf(true));
        	    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        	    
        	    serializer.startTag(null, "favouriteitem");
        	  	serializer.text(message);
        	  	serializer.endTag(null,"favouriteitem");
        	  	serializer.endDocument();
        	  	serializer.flush();
        	  	fileos.close();
    		}
    		else {
    	        
    		    XmlPullParserFactory factory;
    			try {
    				factory = XmlPullParserFactory.newInstance();
    				factory.setValidating(false);
    		        XmlPullParser xpp = factory.newPullParser();
    		        //getFilesDir().getAbsolutePath()
    		        File f = new File(container.getContext().getFilesDir().getAbsolutePath()+"/fav.xml");
    		        //InputStream raw = getActivity().getApplicationContext().getAssets().open("/data/data/com.example.projects/files/fav.xml");
    		        FileInputStream fis = new FileInputStream(f);
    		        xpp.setInput(fis, "UTF-8");
    		        int eventType = xpp.getEventType();
    		        while (eventType != XmlPullParser.END_DOCUMENT) {
    			        if(eventType == XmlPullParser.START_DOCUMENT) {
    			        	System.out.println("start document");	        
    			        } else if(eventType == XmlPullParser.START_TAG) {
    			            //favlist.add(xpp.getName());
    			        	System.out.println("1");
    			        } else if(eventType == XmlPullParser.END_TAG) {
    			            //favlist.add(xpp.getName());
    			        	System.out.println("2");
    			        } else if(eventType == XmlPullParser.TEXT) {
    			            favlist.add(xpp.getText());
        		        	count++;
    			        }
    		        	eventType = xpp.next();
    		        }
    		        Boolean ok = true;
    		        for (int i = 0; i < favlist.size(); i++){
    		        	if(favlist.get(i).equals(message)){
    		        		ok = false;
    		        	}
    		        }
    		        if (ok == true){
    		        	//limits number of favourites allowed as 1 more than the number given
    		        	if(count <= 29){
	    	        		FileOutputStream fileos = new FileOutputStream(newxmlfile);
	    	        	    XmlSerializer serializer = Xml.newSerializer();
	    	        	    
	    	        	    serializer.setOutput(fileos, "UTF-8");
	    	        	    serializer.startDocument("UTF-8", Boolean.valueOf(true));
	    	        	    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
	    	        	    for(int i = 0; i < favlist.size(); i++){
	    	        	    	serializer.startTag(null, "favouriteitem");
	    	        	  		serializer.text(favlist.get(i));
	    	        	  		serializer.endTag(null,"favouriteitem");
	    	        	    }
	    	        	    serializer.startTag(null, "favouriteitem");
	    	        	    serializer.text(message);
	    	        	    serializer.endTag(null, "favouriteitem");
	    	        	  	serializer.endDocument();
	    	        	  	serializer.flush();
	    	        	  	fileos.close();
    		        	}
    		        	else{
    		        		Toast.makeText(container.getContext(), "Favourites is full.", Toast.LENGTH_SHORT).show();
    		        	}
    		        }
    		        else{
    		        	Toast.makeText(container.getContext(), "Item already exists in Favourites.", Toast.LENGTH_SHORT).show();
    		        }
    			} catch (XmlPullParserException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}	

    			
    		}

    	  	//TextView tv = (TextView)findViewById(R.);

    	} catch(Exception e) {
    	     Log.e("Exception","Exception occured in writing");
    	}
        
    }
    
    @Override
    public void onDestroyView() {
    	super.onDestroyView();
    	mPrefs.unregisterOnSharedPreferenceChangeListener(prefListener);
    }
}
